<?php


namespace app\controller\backend;

use app\model\InquiryEmail;
use app\model\WebsiteInquiryEmail;
use app\validate\InquiryEmailValidate;
use think\facade\Db;
use \think\response\Json;

class InquiryEmailController extends BaseController
{

    /**
     * @param InquiryEmail $InquiryEmail
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function index (InquiryEmail $InquiryEmail): Json
    {
        if (request()->isGet()) {
            $siteId = (int)input('website_id');
            if(!$siteId){
                return jsonReturn(-1,'网站ID不能为空');
            }
            $limit = $this->setLimit();
            $where = [
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $siteId,
            ];
            $WebsiteInquiryEmail = new WebsiteInquiryEmail();
            $ids = $WebsiteInquiryEmail->where($where)->column('inquiry_email_id');
            if(empty($ids)){
                return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
            }
            $emailWhere = [
                ['seller_id','=',$this->admin['seller_id']],
                ['id','in',$ids]
            ];

            $inquiryEmail = $InquiryEmail -> where($emailWhere)->paginate($limit)->each(function(&$item)use($WebsiteInquiryEmail){
                $ids = $WebsiteInquiryEmail->where($where = [
                    'seller_id' => $this->admin['seller_id'],
                    'inquiry_email_id' => $item['id'],
                ])->column('website_id');
                $item['website_id'] = $ids;
            });
            return json(['code' => 0, 'msg' => 'ok', 'count' => $inquiryEmail->total(), 'data' => $inquiryEmail->all()]);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * @return Json
     */

    public function save(InquiryEmail $InquiryEmail): Json
    {
        if (request()->isPost()) {
            $param = input('post.');
            try {
                validate(InquiryEmailValidate::class)->scene('save')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $siteIds = $param['website_id'];
            unset($param['website_id']);
            Db::startTrans();
            try{
                $res = $InquiryEmail -> addInquiryEmail($param);
                $inquiryEmail = $res['data'];
                $inquiryEmail->website()->attach($siteIds,['seller_id'=>$param['seller_id']]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(0,'系统错误请重试');
            }

            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * @return Json
     */

    public function update(InquiryEmail $InquiryEmail): Json
    {
        if (request()->isPost()) {
            $param = input('post.');

            try {
                validate(InquiryEmailValidate::class)->scene('update')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            Db::startTrans();
            try{
                $param['seller_id'] = $this->admin['seller_id'];
                $inquiryEmail = $InquiryEmail->getInquiryEmail(['id'=>$param['id'],'seller_id'=>$param['seller_id']])['data'];
                $inquiryEmail->website()->detach();
                $inquiryEmail->website()->attach($param['website_id'],['seller_id'=>$param['seller_id']]);
                $inquiryEmail->email = $param['email'];
                if(isset($param['email'])){
                    $inquiryEmail->status = $param['status'];
                }
                $inquiryEmail->save();
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(-1,'系统错误请重试');
            }

            return jsonReturn(0,'保存成功');
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * @return Json
     */

    public function delete(InquiryEmail $InquiryEmail): Json
    {
        if (request()->isPost()) {
            $param = input('post.');
            $param['seller_id'] = $this->admin['seller_id'];
            try {
                validate(InquiryEmailValidate::class)->scene('read')->check($param);
            } catch (\Exception $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            Db::startTrans();
            try{
                $inquiryEmail = $InquiryEmail->getInquiryEmail(['id'=>$param['id'],'seller_id'=>$param['id']])['data'];
                $inquiryEmail->website()->detach();
                $inquiryEmail->delete();
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(0,'系统错误请重试');
            }

            return jsonReturn(0, '删除成功');
        }
        return jsonReturn(-2, '请求方法错误');
    }
}